//
//  YpViewController.m
//  KIASupervisory
//
//  Created by apple on 15/7/19.
//  Copyright (c) 2015年 MyCompany. All rights reserved.
//

#import "GrzlViewController.h"
#import "MainViewController.h"
#import "SXDetailModel.h"
#import "SXDetailImgModel.h"
#import "SXHTTPManager.h"
#import "LoginViewController.h"
#import "CameraAlbum.h"
#import "NicknameViewController.h"
#import "UIImageView+WebCache.h"

@interface GrzlViewController ()<UIActionSheetDelegate,CameraAlbumDelegate>

@property (nonatomic, strong) NSMutableArray *ypList;
@property (nonatomic, strong) UIButton *back;
@property (nonatomic,strong) SXDetailModel *detailModel;
@property (nonatomic, strong) NetworkManager *networkManager;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, strong) CameraAlbum *cameraAlbum;
@property (nonatomic, strong) NSString *imageStr;



- (IBAction)takePhotoAction:(id)sender;
@end

@implementation GrzlViewController

@synthesize dataList = _dataList;
@synthesize showData = _showData;

- (void)viewDidLoad
{
    [self.navigationController setNavigationBarHidden:YES];
    self.networkManager = [[NetworkManager alloc] init];
    self.detailModel = [[SXDetailModel alloc] init];
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.delegate = self;
    [super viewDidLoad];
    UserInfo *user = [UserInfo instance];
    NSLog(@"@@@@@@@%@",user);
    self.nameText.text = [[user.info objectForKey:@"fullName"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *telStr = [[user.info objectForKey:@"mobile_no"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *zhiweiStr = [[user.info objectForKey:@"zhiwei"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  
    if([user.info objectForKey:@"touxiang"]){
        NSString *image1Str = [NSString stringWithFormat:@"%@%@",SERVER_PATH,[user.info valueForKey:@"touxiang"]];
        NSURL *url1 = [NSURL URLWithString:image1Str];
        [_touxiangImage sd_setImageWithURL:url1];
        SDWebImageManager *manager = [SDWebImageManager sharedManager];
        [manager downloadImageWithURL:url1 options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        }];
    }
    
    self.telText.text = telStr;
    self.cheweiText.text = zhiweiStr;
    
}

- (IBAction)backToPre:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)logout:(id)sender {
    if (self.networkManager == nil) {
        self.networkManager = [[NetworkManager alloc] init];
    }
    theApp.isSet = @"noset";
    [self.networkManager requestWithMethod:logout
                                 parameter:nil delegate:self];
    [self.HUD show:YES];
}

//点击拍照按钮
- (IBAction)takePhotoAction:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                        delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照",@"从相册选择", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
    [actionSheet showInView:self.view];
     
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        [self openSystemCamera];
    }
    else if (buttonIndex==1) {
        [self openSystemImageLib];
    }
}

#pragma mark - Camera
- (void)openSystemCamera{
    if (self.cameraAlbum==nil) {
        self.cameraAlbum = [CameraAlbum instance];
        self.cameraAlbum.delegate = self;
    }
    [self.cameraAlbum openCameraInTargetViewController:self];
}

- (void)openSystemImageLib{
    if (self.cameraAlbum==nil) {
        self.cameraAlbum = [CameraAlbum instance];
        self.cameraAlbum.delegate = self;
    }
    [self.cameraAlbum openPhotoLibraryInTargetViewController:self];
}

#pragma mark - CameraAlbumDelegate
//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this newcontext, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}

- (UIImage *)setTheSeletedImage:(UIImage *)image
{//压缩图片
    UIImage *returnImage = [[UIImage alloc]init];
    //h=720, w=640
    if (image.size.height > image.size.width) {
        if (image.size.height < 640) {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)];
        }else{
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width*640/image.size.height, 640)];
        }
        
    } else {
        if (image.size.width < 640) {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)];
        }else {
            returnImage = [self imageWithImageSimple:image scaledToSize:CGSizeMake(640, image.size.height*640/image.size.width)];
        }
    }
    return returnImage;
    //压缩后图片
}

-(void)getSavedImage:(UIImage*)image {
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    long interval = (long)timeInterval;
    
    UserInfo *user = [UserInfo instance];
    
    NSString *user_id =[user.info objectForKey:@"id"];
    NSString *wtpc = [NSString stringWithFormat:@"%ld",interval];
    NSString *path = [NSString stringWithFormat:@"%@",wtpc];
    
    NSMutableArray *fileList = [NSMutableArray array];
    NSMutableArray *fileNameList = [NSMutableArray array];
            NSData *imgData = nil;
            NSString *imagetype = @".jpeg";
            if (image != nil) {
                if (UIImagePNGRepresentation(image) == nil) {
                    imgData = UIImageJPEGRepresentation(image, 1);
                    imagetype = @".jpeg";
                } else {
                    imgData = UIImagePNGRepresentation(image);
                    imagetype = @".png";
                }
            }
           _imageStr = [NSString stringWithFormat:@"%@/%@%@",path,@"1",imagetype];
            [fileNameList addObject:_imageStr];
            NSDictionary *fileDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                      imgData,@"path",
                                      _imageStr,@"name", nil];
            [fileList addObject:fileDict];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_100.png"]];   // 保存文件的名称
    [UIImagePNGRepresentation(image)writeToFile: filePath    atomically:YES];
    NSString *fileNameListStr = [fileNameList componentsJoinedByString:@","];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           fileList,@"FILE",
                           fileNameListStr,@"touxiang",
                           user_id,@"user_id",
                           path,@"md_input_path", nil];
    [self.networkManager requestWithMethod:updateUserinfo parameter:param delegate:self];

    [self.HUD show:YES];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
}

- (void)refreshViewByReloadData {
    [self getYpList];
}

- (void)getYpList {
    [self.ypList removeAllObjects];
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    
    if (methodId == updateUserinfo) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            if([result isEqualToString:@"000"]){
                 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
                NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic_100.png"]];   // 保存文件的名称
                UIImage *img = [UIImage imageWithContentsOfFile:filePath];
                [_touxiangImage setImage:img];
                UserInfo *user = [UserInfo instance];
                [user.info setValue:_imageStr forKey:@"touxiang"];
            }
        }
        
    } else if(methodId == logout){
        UserInfo *user = [UserInfo instance];
        user.info = nil;
        NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
        [defaults removeObjectForKey:@"username"];
        [defaults removeObjectForKey:@"pwd"];
        [defaults synchronize];
        LoginViewController *problemVC = (LoginViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:problemVC];
        DDMenuController *menuVC = [[DDMenuController alloc] initWithRootViewController:navController];
        [self.navigationController pushViewController:menuVC animated:YES];
    } else if (methodId == getZhuhuListByPhone) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * result = [data objectForKeyOrNil:@"result"];
            if([result isEqualToString:@"000"]){
                NSArray *results = [data objectForKeyOrNil:@"zhuhuList"];
                NSString *stringAll =@"";
                if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                    for(id obj in results){
                        NSString *louStr = [[obj objectForKeyOrNil:@"lou"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        NSString *xiaoquStr = [[obj objectForKeyOrNil:@"xiaoqu"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        NSString *menpaiStr = [[obj objectForKeyOrNil:@"menpai"] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                        stringAll =  [stringAll stringByAppendingFormat:@"%@/%@/%@\n",xiaoquStr, louStr, menpaiStr ];
                        
                    }
                    self.zhuhuText.text = stringAll;
                }
            }
        }
        
    }
}


- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"数据获取失败，请稍后重试";
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_showData count]>0?[_showData count]:0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *TableSampleIdentifier = @"TableSampleIdentifier";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
                             TableSampleIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleDefault
                reuseIdentifier:TableSampleIdentifier];
    }
    if (_showData != nil && _showData.count >0) {
        NSUInteger row = [indexPath row];
        cell.textLabel.text = [_showData objectAtIndex:row];
    }
    return cell;
}
@end